package com.ewing.extranal.im;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.ewing.extranal.im.contant.ImEvent;
import com.ewing.extranal.im.dto.ImRelationInfo;
import com.ewing.extranal.im.dto.ImUserInfo;
import com.ewing.extranal.im.dto.MessageItem;
import com.ewing.extranal.im.dto.MessageTip;
import com.ewing.extranal.im.dto.MessageWrapper;
import com.ewing.extranal.im.service.ImMessageStorager;
import com.ewing.extranal.im.service.ImMessageStoragerImpl;
import com.ewing.extranal.im.service.ImRelation;
import com.ewing.extranal.im.service.ImRelationImpl;
import com.ewing.extranal.im.service.ImService;
import com.ewing.extranal.im.service.ImServiceImpl;
import com.ewing.extranal.im.service.ImUser;
import com.ewing.extranal.im.service.ImUserImpl;
import com.google.gson.Gson;

/**
 * IM的消息控制器
 * 
 * @author tansonlam
 * @createDate 2016年4月22日
 * 
 */
public class ImMessageController {
    private static Logger logger = Logger.getLogger(ImMessageController.class);
    private final ImService imService;
    private final Long imUserId;
    private ImMessageStorager imMessageStorager;
    protected final static Gson gson = new Gson();

    public ImMessageController(Long imUserId) {
        this.imMessageStorager = new ImMessageStoragerImpl();
        this.imService = new ImServiceImpl();
        this.imUserId = imUserId;
    }

    /**
     * 发送联系人列表給登录用户
     */
    public void getContactList() {
        List<ImRelationInfo> relationList = imService.getContactList(imUserId);
        MessageWrapper<List<ImRelationInfo>> messageWapper = new MessageWrapper<List<ImRelationInfo>>(
                ImEvent.RESP_CONTACT, relationList);
        String json = gson.toJson(messageWapper);
        responseMessage(imUserId, json);
    }

    /**
     * 发送指定人的聊天记录
     * 
     * @param relUserId 发送的对象ID
     */
    public void getChatHistory(Long relUserId, String lastMessageId) {
        List<MessageItem> chatHisList = imService
                .getChatHistory(imUserId, relUserId, lastMessageId);

        MessageWrapper<List<MessageItem>> messageWapper = new MessageWrapper<List<MessageItem>>(
                ImEvent.RESP_CHATHIS, chatHisList);
        String json = gson.toJson(messageWapper);
        responseMessage(imUserId, json);
    }

    /**
     * 创建新的聊天会话
     * 
     * @param relUserId
     */
    public void newChat(Long relUserId) {
        ImRelation imRelation = new ImRelationImpl();

        if (imRelation.existRelation(imUserId, relUserId))
            return;

        List<ImRelationInfo> relationList = imService.getContactList(imUserId);
        ImUser imUser = new ImUserImpl();
        ImUserInfo imUserInfo = imUser.getUserInfo(relUserId);
        if (imUserInfo == null)
            return;
        if (relationList == null)
            relationList = new ArrayList<ImRelationInfo>();
        ImRelationInfo imRelationInfo = new ImRelationInfo();
        imRelationInfo.setUserInfo(imUserInfo);
        relationList.add(0, imRelationInfo);
        MessageWrapper<List<ImRelationInfo>> messageWapper = new MessageWrapper<List<ImRelationInfo>>(
                ImEvent.RESP_CONTACT, relationList);
        String json = gson.toJson(messageWapper);
        responseMessage(imUserId, json);
    }

    /**
     * 发送聊天信息
     * 
     * @param relUserId 发送的对象ID
     * @param message 发送消息
     * @param msg
     */
    public void recordMessage(Long relUserId, String message) {

        imMessageStorager.recordMessage(imUserId, relUserId, message);
        // 发送给自已，提示拉取聊天记录
        responseMessage(imUserId, gson.toJson(new MessageWrapper<MessageTip>(imUserId,
                ImEvent.RESP_NEWMSG,
                new MessageTip(ImMessageNotReadPool.count(imUserId), relUserId))));
        // 发送给接收方，提示拉取聊天记录
        responseMessage(relUserId, gson.toJson(new MessageWrapper<MessageTip>(relUserId,
                ImEvent.RESP_NEWMSG,
                new MessageTip(ImMessageNotReadPool.count(relUserId), imUserId))));

    }

    /**
     * 发送消息给指定用户
     * 
     * @param imUserId
     * @param msg
     */
    private void responseMessage(Long imUserId, String msg) {
        ImMessageWebSocket client = null;
        try {
            client = ImConnectionPool.get(imUserId);
            if (client == null)
                throw new IOException("not found imUserId:" + imUserId);
            synchronized (client) {
                client.getSession().getBasicRemote().sendText(msg);
            }
        } catch (IOException e) {
            logger.debug("Chat Error: Failed to send message to client", e);
            ImConnectionPool.remove(imUserId);
            if (client != null) {
                try {
                    client.getSession().close();
                } catch (IOException e1) {
                    // Ignore
                }
            }
        }
    }

    /**
     * 标记消息为已读
     * 
     * @param messageId
     * @return
     */
    public Boolean update2Read(Long relUserId, String[] messageIds) {
        for (String messageId : messageIds) {
            imService.update2Read(imUserId, relUserId, messageId);
        }
        responseMessage(imUserId, gson.toJson(new MessageWrapper<MessageTip>(imUserId,
                ImEvent.RESP_NEWMSG,
                new MessageTip(ImMessageNotReadPool.count(imUserId), relUserId))));
        return true;
    }
}
